﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using SubSonic;

public partial class User_Employer_ChangeUsername : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Lblstatus.Text = "";
        var thisUser = HttpContext.Current.User;
        if (thisUser.Identity.IsAuthenticated)
        {
            if (thisUser.IsInRole("edituser"))
            {
                RadioButtonListRole.Items[2].Enabled = false;
            }
            else
            {
                RadioButtonListRole.Items[2].Enabled = true;
            }
        }
        
    }
    protected void RadioButtonListRole_SelectedIndexChanged(object sender, EventArgs e)
    {
        PanelEdit.Visible = false;
        GridViewUsers.Enabled = true;
        GridViewUsers.DataBind();
        if (RadioButtonListRole.SelectedItem.Value == "Advisor")
        {
        
            RadioButtonListAdvisors.Visible = true;
            RadioButtonListSurveyor.Visible = false;
        }
        else if (RadioButtonListRole.SelectedItem.Value == "Surveyor")
        {
         
            RadioButtonListAdvisors.Visible = false;
            RadioButtonListSurveyor.Visible = true;
        }
        else
        {
       
            RadioButtonListSurveyor.Visible = false;
            RadioButtonListAdvisors.Visible = false;
        }
    }
    protected void RadioButtonListAdvisors_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        try
        {
            BindingGrid();
        }
        catch
        { }
    }

    private void BindingGrid()
    {
        string orderExpression = DataAccess.TblUserDetail.Columns.Name;
        Query tempQuery = new Query(DataAccess.TblUserDetail.Schema);
        tempQuery.OrderBy = SubSonic.OrderBy.Asc("Name");
        if (ViewState["SortExpression"] != null && !ViewState["SortExpression"].ToString().Trim().Equals(String.Empty))
        {
            switch (ViewState["SortExpression"].ToString())
            {
                case "Name":
                    orderExpression = DataAccess.TblUserDetail.Columns.Name;
                    break;
                case "Family":
                    orderExpression = DataAccess.TblUserDetail.Columns.Family;
                    break;
                case "UserName":
                    orderExpression = DataAccess.TblUserDetail.Columns.UserName;
                    break;
            }

            tempQuery.OrderBy = ViewState["SortDirection"] != "Ascending" ? SubSonic.OrderBy.Desc(orderExpression) : SubSonic.OrderBy.Asc(orderExpression);
        }
        if (RadioButtonListRole.SelectedItem.Value == "Other")
        {
            SubSonic.Query q = DataAccess.TblUserDetail.CreateQuery();
            q.QueryType = SubSonic.QueryType.Select;
            q.OrderBy = tempQuery.OrderBy;
            List<string> roles = new List<string>() { "Employer", "FourthFactor", "BonyadShahrestan", "EditUser", "ViewUser" };
            q.AddWhere(DataAccess.TblUserDetail.Columns.Family, SubSonic.Comparison.Like, "%" + TxtFamily.Text + "%")
                .AND(DataAccess.TblUserDetail.Columns.Role, Comparison.In, roles);
            DataSet dt = q.ExecuteDataSet();
            if (dt.Tables[0].Rows.Count > 0)
            {
                GridViewUsers.DataSource = dt;
                GridViewUsers.DataBind();
            }
            else
            {
                Lblstatus.Text = " <script>alert('.فرد مورد نظر یافت نشد ')</script>";
            }
        }
        if (RadioButtonListRole.SelectedItem.Value == "Advisor")
        {
            if (RadioButtonListAdvisors.SelectedItem.Value == "hoghooghi")
            {
                SubSonic.Query q = DataAccess.TblUserDetail.CreateQuery();
                q.QueryType = SubSonic.QueryType.Select;
                q.OrderBy = tempQuery.OrderBy;
                q.AddWhere(DataAccess.TblUserDetail.Columns.Family, SubSonic.Comparison.Like, "%" + TxtFamily.Text + "%");
                q.AddWhere(DataAccess.TblUserDetail.Columns.Role, SubSonic.Comparison.Equals, "Advisorhoghooghi");
                DataSet dt = q.ExecuteDataSet();
                if (dt.Tables[0].Rows.Count > 0)
                {
                    GridViewUsers.DataSource = dt;
                    GridViewUsers.DataBind();
                }
                else
                {
                    Lblstatus.Text = " <script>alert('.فرد مورد نظر یافت نشد ')</script>";
                }
            }
            if (RadioButtonListAdvisors.SelectedItem.Value == "haghighi")
            {
                SubSonic.Query q = DataAccess.TblUserDetail.CreateQuery();
                q.QueryType = SubSonic.QueryType.Select;
                q.OrderBy = tempQuery.OrderBy;
                q.AddWhere(DataAccess.TblUserDetail.Columns.Family, SubSonic.Comparison.Like, "%" + TxtFamily.Text + "%");
                q.AddWhere(DataAccess.TblUserDetail.Columns.Role, SubSonic.Comparison.Equals, "Advisorhaghighi");
                DataSet dt = q.ExecuteDataSet();
                if (dt.Tables[0].Rows.Count > 0)
                {
                    GridViewUsers.DataSource = dt;
                    GridViewUsers.DataBind();
                }
                else
                {
                    Lblstatus.Text = " <script>alert('.فرد مورد نظر یافت نشد ')</script>";
                }
            }
        }
        if (RadioButtonListRole.SelectedItem.Value == "Surveyor")
        {
            if (RadioButtonListSurveyor.SelectedItem.Value == "Advisorhoghooghi")
            {
                SubSonic.Query q = DataAccess.TblUserDetail.CreateQuery();
                q.QueryType = SubSonic.QueryType.Select;
                q.OrderBy = tempQuery.OrderBy;
                q.AddWhere(DataAccess.TblUserDetail.Columns.Family, SubSonic.Comparison.Like, "%" + TxtFamily.Text + "%");
                q.AddWhere(DataAccess.TblUserDetail.Columns.Role, SubSonic.Comparison.Equals, "Surveyorhoghooghi");
                DataSet dt = q.ExecuteDataSet();
                if (dt.Tables[0].Rows.Count > 0)
                {
                    GridViewUsers.DataSource = dt;
                    GridViewUsers.DataBind();
                }
                else
                {
                    Lblstatus.Text = " <script>alert('.فرد مورد نظر یافت نشد ')</script>";
                }
            }
            if (RadioButtonListSurveyor.SelectedItem.Value == "Advisorhaghighi")
            {
                SubSonic.Query q = DataAccess.TblUserDetail.CreateQuery();
                q.QueryType = SubSonic.QueryType.Select;
                q.OrderBy = tempQuery.OrderBy;
                q.AddWhere(DataAccess.TblUserDetail.Columns.Family, SubSonic.Comparison.Like, "%" + TxtFamily.Text + "%");
                q.AddWhere(DataAccess.TblUserDetail.Columns.Role, SubSonic.Comparison.Equals, "Surveyorhaghighi");
                DataSet dt = q.ExecuteDataSet();
                if (dt.Tables[0].Rows.Count > 0)
                {
                    GridViewUsers.DataSource = dt;
                    GridViewUsers.DataBind();
                }
                else
                {
                    Lblstatus.Text = " <script>alert('.فرد مورد نظر یافت نشد ')</script>";
                }
            }
        }
    }

    protected void GridViewUsers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            int id = Convert.ToInt32(e.CommandArgument);
            switch (e.CommandName)
            {
                case "Select":
                    Guid userid = new Guid(GridViewUsers.DataKeys[id].Value.ToString());
                    string NameFamily = GridViewUsers.Rows[id].Cells[0].Text + " " + GridViewUsers.Rows[id].Cells[1].Text;
                    Session["UserId"] = userid;
                    string Username = GridViewUsers.Rows[id].Cells[5].Text;
                    Session["Username"] = Username;
                    GridViewUsers.Enabled = false;
                    PanelEdit.Visible = true;
                    break;

                //if (RadioButtonListRole.SelectedItem.Value == "Advisor")
                //{
                //    if (RadioButtonListAdvisors.SelectedItem.Value == "hoghooghi")
                //    {

                //    }
                //    else if (RadioButtonListAdvisors.SelectedItem.Value == "haghighi")
                //    {

                //    }
                //}

                //else
                //{
                //}


            }
        }
        catch
        {

        }
    }
    protected void ButtonReg_Click(object sender, EventArgs e)
    {

        GridViewUsers.Enabled = true;
        PanelEdit.Visible = false;
        object mu = Membership.GetUser(Session["Username"].ToString()).ProviderUserKey;
        if (Membership.GetUser(Session["Username"].ToString()) != null)
        {
            if (Membership.GetUser(TextBoxUserName.Text) == null)
            {
                SubSonic.Query q = DataAccess.TblUserDetail.CreateQuery();
                SubSonic.Query q1 = DataAccess.AspnetUser.CreateQuery();
                q.QueryType = SubSonic.QueryType.Update;
                q1.QueryType = SubSonic.QueryType.Update;
                q.AddUpdateSetting(DataAccess.TblUserDetail.Columns.UserName, TextBoxUserName.Text);
                q1.AddUpdateSetting(DataAccess.AspnetUser.Columns.UserName, TextBoxUserName.Text);
                q1.AddUpdateSetting(DataAccess.AspnetUser.Columns.LoweredUserName, TextBoxUserName.Text.ToLower());
                q.AddWhere(DataAccess.TblUserDetail.Columns.UserId, mu);
                q1.AddWhere(DataAccess.AspnetUser.Columns.UserId, mu);
                q1.OR(DataAccess.AspnetUser.Columns.UserName, Session["Username"].ToString());
                SubSonic.Query q2 = DataAccess.TblTask.CreateQuery();
                q2.QueryType = SubSonic.QueryType.Update;
                q2.AddUpdateSetting(DataAccess.TblTask.Columns.UserName, TextBoxUserName.Text);
                q2.AddWhere(DataAccess.TblTask.Columns.UserName, Session["Username"].ToString());
                q2.Execute();
                q.Execute();
                q1.Execute();
                Lblstatus.Text = " <script>alert('.ثبت نام کاربری با موفقیت انجام شد')</script>";
                GridViewUsers.DataBind();
                //= new FormsAuthenticationTicket();
                //  FormsIdentity i = new FormsIdentity();
                //FormsAuthenticationTicket s=  i.Ticket;

            }
            else
            {
                Lblstatus.Text = " <script>alert('.نام کاربری جدید قبلا تعریف شده است')</script>";
                TextBoxUserName.Text = "";
                TextBoxUserNameConfirm.Text = "";
            }
        }
        else
        {
            Lblstatus.Text = " <script>alert('.نام کاربری مورد نظر شما موجود نیست')</script>";
            TextBoxUserName.Text = "";
            TextBoxUserNameConfirm.Text = "";

        }
    }
    protected void ButtonCancel_Click(object sender, EventArgs e)
    {
        PanelEdit.Visible = false;
        GridViewUsers.Enabled = true;

        TextBoxUserName.Text = "";
        TextBoxUserNameConfirm.Text = "";
        RadioButtonListAdvisors.Visible = false;
        RadioButtonListRole.ClearSelection();
    }
    protected void GridViewUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    {
          if (e.Row.RowType == DataControlRowType.DataRow)
        {
            IDataReader dr= DataAccess.TblUserDetail.FetchByParameter(DataAccess.TblUserDetail.Columns.UserName, e.Row.Cells[5].Text);
            if (dr.Read())
            {
                if (dr["Role"].ToString() == "Surveyorhaghighi")
                    e.Row.Cells[6].Text = "نقشه بردار حقیقی";
                if (dr["Role"].ToString() == "Surveyorhoghooghi")
                    e.Row.Cells[6].Text = "نقشه بردار حقوقی";
                if (dr["Role"].ToString() == "Advisorhaghighi")
                    e.Row.Cells[6].Text = "مشاور حقیقی";
                if (dr["Role"].ToString() == "Advisorhoghooghi")
                    e.Row.Cells[6].Text = "مشاور حقوقی";
                if (dr["Role"].ToString() == "Employer")
                    e.Row.Cells[6].Text = "کارفرما";
                if (dr["Role"].ToString() == "FourthFactor")
                    e.Row.Cells[6].Text = "عامل چهار";
                if (dr["Role"].ToString() == "BonyadShahrestan")
                    e.Row.Cells[6].Text = "بنیاد شهرستان";
                if (dr["Role"].ToString() == "EditUser")
                    e.Row.Cells[6].Text = "کاربر عادی ویرایش و ثبت";
                if (dr["Role"].ToString() == "ViewUser")
                    e.Row.Cells[6].Text =  "کاربر عادی فقط مشاهده";
                dr.Close();
            }
        }
    }
    protected void GridViewUsers_OnSort(object sender, GridViewSortEventArgs e)
    {
        // get values from viewstate
        String sortExpression = ViewState["SortExpression"] as string;
        String sortDirection = ViewState["SortDirection"] as string;

        // on first time header clicked ( including different header), sort ASCENDING
        if (e.SortExpression != sortExpression)
        {
            sortExpression = e.SortExpression;
            sortDirection = "Ascending";
        }
        // on second time header clicked, toggle sort
        else
        {
            if (sortDirection == "Ascending")
            {
                sortExpression = e.SortExpression;
                sortDirection = "Descending";
            }
            // Descending
            else
            {
                sortExpression = e.SortExpression;
                sortDirection = "Ascending";
            }
        }

        // save state for next time

        ViewState["SortExpression"] = sortExpression;
        ViewState["SortDirection"] = sortDirection;
        BindingGrid();
    }

}